﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using StockFinder.UI.Views;
using StockFinder.Services.Extractors;
using StockFinder.Services.Extractors.Yahoo;
using StockFinder.DataAccess;
using StockFinder.Model;
using System.Threading;

namespace StockFinder.UI.Controllers
{
    public class DownloadSymbolsViewController
    {
        private readonly IDownloadSymbolsView _View;
        private readonly ISymbolExtractor _SymbolExtractor;
        private readonly IndexUrlDataAccess _IndexUrlDataAccess;
        private readonly SymbolDataAccess _SymbolDataAccess;

        public DownloadSymbolsViewController(IDownloadSymbolsView view)
        {
            _View = view;

            _SymbolExtractor = new YahooSymbolExtractor();
            _IndexUrlDataAccess = new IndexUrlDataAccess();
            _SymbolDataAccess = new SymbolDataAccess();

            _View.StartDownload += new EventHandler(OnViewStartDownload);
            _SymbolExtractor.LogUpdate += new Action<string>(_SymbolExtractor_LogUpdate);
        }

        /// <summary>
        /// Occurs when the extractor has a message
        /// </summary>
        /// <param name="message"></param>
        void _SymbolExtractor_LogUpdate(string message)
        {
            _View.AppendLog(message);
        }

        void OnViewStartDownload(object sender, EventArgs e)
        {
            //invoke this in separate thread to stop UI from hanging
            Thread thread = new Thread(new ThreadStart(delegate
            {
                _View.AppendLog("Getting list of urls");

                //first get the list of index urls
                List<IndexUrl> indexUrls = _IndexUrlDataAccess.GetAllIndexUrls();

                List<string> symbolList = new List<string>();

                int counter = 0;

                _View.ResetProgress();

                //extract all symbols from url
                foreach (IndexUrl indexUrl in indexUrls)
                {
                    symbolList.AddRange(_SymbolExtractor.ExtractSymbolsFromUrl(indexUrl.Url));

                    //update progress on view
                    _View.UpdateProgress(0, indexUrls.Count, counter++);
                }

                //get list of existing symbols from database
                List<Symbol> symbols = SymbolDataAccess.GetAllSymbols();

                List<string> newSymbols = new List<string>();

                //merge list: new, not exist, exist
                foreach (string symbol in symbolList)
                {
                    //find matching symbol
                    Symbol existingSymbol = symbols.Find(s => s.Name == symbol);

                    //doesnt exist?
                    if (existingSymbol == null)
                    {
                        //insert the new symbol
                        SymbolDataAccess.InsertSymbol(symbol);

                        //add to list
                        newSymbols.Add(symbol);

                        _View.AppendLog(string.Format("Inserted new symbol: {0}", symbol));
                    }
                }

                _View.AppendLog("Completed");
            }));

            thread.Name = "DownloadSymbolsFromUrlThread";
            thread.Start();             
        }
    }
}
